#include "IRequest.h"
#ifdef WIN32
#include <Windows.h>
#endif
using namespace std;

IRequest::IRequest(Client *aClient)
	: mClient(aClient),
	  mResponse(nullptr)
{
	cout << "IRequest Constructed. You're an idiot" << endl;
}

IRequest::IRequest()
	: mClient(nullptr),
	  mResponse(nullptr)
{

}


IRequest::~IRequest(void)
{
	if(mClient != nullptr)
	{
		delete mClient;
	}
	if(mResponse != nullptr)
	{
		delete mResponse;
	}
#ifdef WIN32
	cout << "IRequest deconstructed: " << (GetTickCount() - TickStart) << "ms" << endl;
#else
    cout << "IRequest deconstructed " << endl;
#endif
}

bool IRequest::Call()
{
	if(ProcessHeader())
	{
		if(PrepareResponse())
		{
			if(DoResponse())
			{
				if(Output())
				{
					if(Die())
					{
						Running = false;
						return true;
					}
					cout << "Die Failed" << endl;
				}
				cout << "Output Failed" << endl;
			}
			cout << "DoResponse Failed" << endl;
		}
		cout << "Prepare Failed" << endl;
	}
	// ERROR If an error occured and we haven't sent headers yet, send 500 Internal Server Error
	cout << "Process Failed" << endl;
	cout << "Error processing request, not a lot we can do since we're in a different thread" << endl;
	Running = false;
	return false;
}

bool IRequest::operator()(void)
{
	Started = true;
	Running = true;
	// Now we create a new thread and run Call.
	mWorkerThread = boost::thread(&IRequest::Call, this);
	return true;
}

bool IRequest::IsStarted()
{
	return Started;
}
bool IRequest::IsRunning()
{
	return Running;
}

void IRequest::Initialise()
{
	Running = Started = false;
#ifdef WIN32
	TickStart = GetTickCount();
#endif
}